clear all;

nobs = 1000; % number of Monte Carlo draws in our simulated universe
randn('seed',1); 
bmax = 12; % max true number of bidders we allow
draws = normrnd(0,1,nobs,bmax); % generate our universe of random draws
alpha = 0.7; % position-to-position decline in CTR

lookupt = [];

for nbids = 4:bmax
    for m = [0.05:0.01:1.00 1.10:0.10:10.00 10.25:0.25:20.00] % discrete grid of various potential means of the "true" distribution
        for stdrat = 0.1:0.1:1 % various potential ratios of std.dev. to mean of the "true" distribution

            v = (m*stdrat)^2; % the corresponding variance of the "true" distribution

            % Generate the profile of random draws, sorted
            mu = log((m^2)/sqrt(v+m^2));
            sigma = sqrt(log(v/(m^2)+1));
            vals = exp(mu + sigma*sort(draws(:,1:nbids),2));
            
            % Count the number of bidders above the old reserve price for each observation
            bstats = (sum(vals>0.1,2));
            
            % Now iteratively compute equilibrium bids, using the formula from EOS (2007) modified for the case with reserve prices
            vals = max(vals, 0.1);
            bids = alpha*0.10 + (1-alpha)*vals(:,1);
            for i = 2:(nbids-1)
                bids = [bids alpha*bids(:,i-1)+(1-alpha)*vals(:,i)];
            end
            
            % Now compute the summary statistics for these draws, keeping in mind that
            % observed numbers of bidders will be different for different draws
            mstats =[];
            stdstats =[];
            for i = 1:nobs
                if bstats(i) > 1
                    mstats = [mstats; mean(bids(i,(nbids-bstats(i)+1):nbids-1))];
                    stdstats = [stdstats; std(bids(i,(nbids-bstats(i)+1):nbids-1))];
                end
            end
            
            mbstats = mean(bstats);
            if mbstats > 3 
                lookupt = [lookupt; [nbids m stdrat mean(bstats) mean(mstats) mean(stdstats)]];
            end
        end
    end
end

% Save the lookup table, both as a text file and a Matlab file
writematrix(lookupt);
save lookupt.mat lookupt
